 //
//  JGGView.m
//  IHK
//
//  Created by 郑文明 on 16/3/14.
//  Copyright © 2016年 郑文明. All rights reserved.
//

#import "JGGView.h"
#import "UIImageView+WebCache.h"
#import <MediaPlayer/MediaPlayer.h>
#define kGAP 10
#define kAvatar_Size 40

@implementation JGGView

- (instancetype)initWithFrame:(CGRect)frame dataSource:(NSArray *)dataSource completeBlock:(TapBlcok )tapBlock
{
    self = [super initWithFrame:frame];
    if (self) {
        
        
        for (NSUInteger i=0; i<dataSource.count; i++) {
            UIImageView *iv = [[UIImageView alloc]initWithFrame:CGRectMake(0+([self imageWidth]+kJGG_GAP)*(i%3),floorf(i/3.0)*([self imageWidth]+kJGG_GAP),[self imageWidth], [self imageWidth])];
            if ([dataSource[i] isKindOfClass:[UIImage class]]) {
                iv.image = dataSource[i];
            }else if ([dataSource[i] isKindOfClass:[NSString class]]){
                [iv sd_setImageWithURL:[NSURL URLWithString:[Helper ChineseUrlForUT8Url:dataSource[i]]] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            }else if ([dataSource[i] isKindOfClass:[NSURL class]]){
                [iv sd_setImageWithURL:dataSource[i] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            }
            self.dataSource = dataSource;
            self.tapBlock = tapBlock;// 一定要给self.tapBlock赋值
            iv.userInteractionEnabled = YES;//默认关闭NO，打开就可以接受点击事件
            iv.tag = i;
            [self addSubview:iv];
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImageAction:)];
            [iv addGestureRecognizer:singleTap];
        }
    }
    return self;
}
-(void)JGGView:(JGGView *)jggView DataSource:(NSArray *)dataSource completeBlock:(TapBlcok)tapBlock
{
    
    NSMutableArray *arrM = [NSMutableArray arrayWithArray:dataSource];
    
    for (id data in dataSource) {
        if ([data isKindOfClass:[NSString class]] && [NSString stringWithFormat:@"%@",data].length == 0) {
            
            [arrM removeObject:data];
            
        }
    }
    
    ///解决图片复用问题
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CGFloat itemW = [self itemWidthForPicPathArray:arrM];
    
    
    CGFloat jjg_height = 0.0;
    CGFloat jjg_width = 0.0;
    
    if (arrM.count>0&&arrM.count<=3) {
        jjg_height = itemW;
        jjg_width  = 3*(itemW+kJGG_GAP)-kJGG_GAP;;
    }else if (arrM.count>3&&arrM.count<=6){
        jjg_height = 2*(itemW+kJGG_GAP)-kJGG_GAP;
        jjg_width  = 3*(itemW+kJGG_GAP)-kJGG_GAP;
    }else  if (arrM.count>6){
        
        NSInteger row;
        if (arrM.count%3 == 0) {
            row = arrM.count/3;
        }else
        {
            row = arrM.count/3  + 1;
        }
        
        jjg_height = row *(itemW+kJGG_GAP)-kJGG_GAP;
        jjg_width  = 3*(itemW+kJGG_GAP)-kJGG_GAP;
    }

    
        for (NSUInteger i=0; i<arrM.count; i++) {
            UIImageView *iv = [UIImageView new];
            
            
            iv.contentMode = UIViewContentModeScaleAspectFill;
            
            iv.clipsToBounds = YES;
            
            if ([arrM[i] isKindOfClass:[UIImage class]]) {
                
                iv.image = arrM[i];
                
            }else if ([arrM[i] isKindOfClass:[NSString class]]){
//                NSString *imageUrl = [dataSource[i] substringFromIndex:1];
                //显示网上获取的图片[NSURL URLWithString:[URL_HEARD stringByAppendingString:imageUrl]]
                [iv sd_setImageWithURL:[NSURL URLWithString:[Helper ChineseUrlForUT8Url:arrM[i]]] placeholderImage:PlaceHold];
                
            }else if ([arrM[i] isKindOfClass:[NSURL class]]){
                
                [iv sd_setImageWithURL:arrM[i] placeholderImage:PlaceHold
                 ];
                
            }else if ([arrM[i] isKindOfClass:[NSData class]])
            {
                iv.image = [UIImage imageWithData:arrM[i]];
            }
            
            jggView.dataSource = arrM;
            jggView.tapBlock = tapBlock;
            iv.userInteractionEnabled = YES;//默认关闭NO，打开就可以接受点击事件
            iv.tag = i;
            [jggView addSubview:iv];
            //九宫格的布局
            CGFloat  Direction_X = ((itemW+kJGG_GAP)*(i%3));
            CGFloat  Direction_Y  = (floorf(i/3.0)*(itemW+kJGG_GAP));
            
            [iv mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(jggView).offset(Direction_X);
                make.top.mas_equalTo(jggView).offset(Direction_Y);
                make.size.mas_equalTo(CGSizeMake(itemW, itemW));
            }];
            
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:jggView action:@selector(tapImageAction:)];
            [iv addGestureRecognizer:singleTap];
            
            
            if (arrM.count == 1) {
                if ([arrM[0] containsString:@"video_"]) {
                    

                    
                    iv.image = PlaceHold;
                    
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        // 处理耗时操作的代码块...
                        
                        UIImage *image = [Helper thumbnailImageForVideo:[NSURL URLWithString:arrM[0]] atTime:1];
                        //通知主线程刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //回调或者说是通知主线程刷新，
                            
                            iv.image = image;
                        });

                        
                        
                    });
                            
                    UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                    
                    
                    
                    //            playBtn.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
                    
                    [playBtn setImage:[UIImage imageNamed:@"icon_video"] forState:UIControlStateNormal];
                    
                    [playBtn addTarget:self action:@selector(playVideo) forControlEvents:UIControlEventTouchUpInside];
                    
                    [iv addSubview:playBtn];

                    [playBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.edges.mas_equalTo(iv);
                    }];
                }
            }
            
            
            //处理视频或图片
//            if ([[arrM[0] pathExtension] isEqualToString:@"mp4"] || ![[arrM[0] pathExtension] isEqualToString:@"png"]) {
//

//            }else
//            {
//
//            }

//
        }
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(jjg_width, jjg_height));
        
    }];
    
}
#pragma mark
#pragma mark 配置图片的宽高

//+(CGFloat)imageWidth{
//    return ([UIScreen mainScreen].bounds.size.width-(2*kGAP+kAvatar_Size)*2)/3;
//}
//+(CGFloat)imageHeight{
//    return ([UIScreen mainScreen].bounds.size.width-(2*kGAP+kAvatar_Size)*2)/3;
//}

- (CGFloat)itemWidthForPicPathArray:(NSArray *)array
{
    if (array.count == 1) {
        self.imageWidth = 120;
        return 120;
    } else {
        CGFloat itemW = ([UIScreen mainScreen].bounds.size.width-(2*kGAP+kAvatar_Size)*2)/3 ;
        self.imageWidth = itemW;
        return itemW;
    }
}


-(void)tapImageAction:(UITapGestureRecognizer *)tap{
    UIImageView *tapView = (UIImageView *)tap.view;
    
    SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
    photoBrowser.delegate = self;
    photoBrowser.currentImageIndex = tapView.tag;
    photoBrowser.imageCount = _dataSource.count;
    photoBrowser.sourceImagesContainerView = self;
    [photoBrowser show];
    
    
//    if (self.tapBlock) {
//        self.tapBlock(tapView.tag,self.dataSource,self.indexpath);
//    }
}

-(void)playVideo
{
    if (self.tapBlock) {
        self.tapBlock(1,self.dataSource,self.indexpath);
    }
    // 设置视频播放器
    MPMoviePlayerViewController *moviePlayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:[self.dataSource lastObject]]];
    
    [moviePlayerController.moviePlayer prepareToPlay];
    moviePlayerController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
    [self.viewController presentMoviePlayerViewControllerAnimated:moviePlayerController];
    

}
#pragma mark - SDPhotoBrowserDelegate

- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
//    NSString *urlString = self.dataSource[index];
//    return [NSURL URLWithString:urlString];
    NSData *imageName = [Helper scaleImage:self.dataSource[index] toKb:200];
    NSURL *url = [NSURL URLWithString:[[NSString alloc]initWithData:imageName encoding:NSUTF8StringEncoding ]];
    
    return url;
}
- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    UIImageView *imageView = self.subviews[index];
    return imageView.image;
}
@end
